package com.yiwenup.leetcode.offer;

import com.yiwenup.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
 **/
public class No034 {

    private List<List<Integer>> res = new ArrayList<>();
    private LinkedList<Integer> path = new LinkedList<>();

    /**
     * 执行用时：1 ms, 在所有 Java 提交中击败了99.99%的用户
     * 内存消耗：38.4 MB, 在所有 Java 提交中击败了95.19%的用户
     */
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        preOrder(root, target);
        return res;
    }

    public void preOrder(TreeNode node, int target) {
        if (node == null || target - node.val < 0) return;

        target -= node.val;
        path.add(node.val);
        if (target == 0 && node.left == null && node.right == null) res.add(new LinkedList<>(path));

        if (node.left != null) preOrder(node.left, target);
        if (node.right != null) preOrder(node.right, target);
        path.removeLast();
    }
}
